package com.jsoup.realm;

import com.jsoup.bean.User;
import com.jsoup.constant.RoleConstant;
import com.jsoup.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

public class DatabaseRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    private final static Logger logger = LoggerFactory.getLogger(DatabaseRealm.class);

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        logger.info("【用户授权】doGetAuthorizationInfo...");
        User user = (User) principalCollection.getPrimaryPrincipal();

        if (user != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            if (user.getUserLevelId() == RoleConstant.ADMIN_LEVEL) {
                info.addRole(RoleConstant.ROLE_ADMIN);
                info.addRole(RoleConstant.ROLE_USER);
            }
            // 赋予用户角色
            if (user.getUserLevelId() == RoleConstant.USER_LEVEL) {
                info.addRole(RoleConstant.ROLE_USER);
            }
            return info;
        }
        return null;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        logger.info("【用户认证】doGetAuthenticationInfo...");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User u = new User();
        u.setUserName(token.getUsername());
        User user = userService.getUser(u);
        if (user == null) {
            throw new UnknownAccountException("账户不存在");
        }
        return new SimpleAuthenticationInfo(user, user.getUserPassword(), ByteSource.Util.bytes(user.getUserName()), getName());
    }
}